package cn.cloudreal.cbms.castDetail.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.castDetail.service.CastDetailService;
import cn.cloudreal.cbms.castDetail.service.ChargeService;
import cn.cloudreal.cbms.common.util.Arith;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.StringUtils;
import cn.cloudreal.cbms.resmonitor.service.ResMonitorService;
import cn.cloudreal.cbms.vo.Charge;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.FundBudget;
import cn.cloudreal.cbms.vo.LevelRule;
import cn.cloudreal.cbms.vo.ProjectMedium;
import cn.cloudreal.cbms.vo.SourcePlanYear;

import com.opensymphony.xwork2.ActionSupport;

public class ChargeAction extends ActionSupport
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    /** 费用类型 */
    private List<Dictionary> dics;
    /** 资金类型 */
    private List<Dictionary> fundTypes;
    /** 费用子类 */
    private List<Dictionary> costSubtypes;
    /** 下拉框类型 */
    private String selectType;
    /** 父节点id */
    private String parentId;
    /** 费用列表 */
    private List<Charge> charges;
    /** 媒体价格id */
    private Integer priceId;
    /** 费用类型 */
    private String costType;
    /** 费用子类 */
    private String costSubtype;
    /** 资金类型 */
    private String fundType;
    /** 项目媒介id */
    private Integer proMedID;
    /** 资源监控服务 */
    private ResMonitorService resMonitorService;
    /** 资源预算 */
    //private SourcePlanYear sourceplanyear;
    /** 项目媒介服务类 */
    private CastDetailService castDetailService;
    /** 项目媒介信息 */
    private ProjectMedium projectMedium;
    /** 预算使用折扣 */
    //private Float unPromotionUsedRatio;
    /** 项目费用服务类 */
    private ChargeService chargeService;
    /** 数据字典 */
    private Dictionary dictionary;
    
    public Dictionary getDictionary()
    {
        return dictionary;
    }

    public void setDictionary(Dictionary dictionary)
    {
        this.dictionary = dictionary;
    }

    /** 项目费用实体 */
    private Charge charge;
    
    /** 项目费用实体 */
    private FundBudget fundBudget;

    public String getFundType()
    {
        return fundType;
    }

    public void setFundType(String fundType)
    {
        this.fundType = fundType;
    }
    public FundBudget getFundBudget()
    {
        return fundBudget;
    }

    public void setFundBudget(FundBudget fundBudget)
    {
        this.fundBudget = fundBudget;
    }

    public Charge getCharge()
    {
        return charge;
    }

    public void setCharge(Charge charge)
    {
        this.charge = charge;
    }

    public ChargeService getChargeService()
    {
        return chargeService;
    }

    public void setChargeService(ChargeService chargeService)
    {
        this.chargeService = chargeService;
    }

    public ProjectMedium getProjectMedium()
    {
        return projectMedium;
    }

    public void setProjectMedium(ProjectMedium projectMedium)
    {
        this.projectMedium = projectMedium;
    }

    public CastDetailService getCastDetailService()
    {
        return castDetailService;
    }

    public void setCastDetailService(CastDetailService castDetailService)
    {
        this.castDetailService = castDetailService;
    }

    public Integer getProMedID()
    {
        return proMedID;
    }

    public void setProMedID(Integer proMedID)
    {
        this.proMedID = proMedID;
    }

    public ResMonitorService getResMonitorService()
    {
        return resMonitorService;
    }

    public void setResMonitorService(ResMonitorService resMonitorService)
    {
        this.resMonitorService = resMonitorService;
    }

    /**
     * 费用页面初始化
     * 
     * @return
     */
    public String init()
    {
        // 资金类型
        //fundTypes = DatadicContext.getInstance().getSubDatadicByCode("-1", "ZJLX");

        // 费用类型
        Map condition = new HashMap();
        condition.put("proMedID", proMedID);
        dics = chargeService.getCostTypeByProMedID(condition);
        if(dics == null)
        {
            dics = new ArrayList<Dictionary>();
        }
        
        // 取得项目媒介刊例总价
        projectMedium = chargeService.getProjectMediumByProMedID(proMedID);
        
        return SUCCESS;
    }
    
    /**
     * 费用新增
     * 
     * @return
     * @throws IOException 
     */
    public String addCharges() throws IOException
    {
        try{
            chargeService.saveProjectMedioPrice(charges);
        }catch (Exception e) {
              e.printStackTrace();
              int error = e.getMessage().indexOf("INSERT 语句与 FOREIGN KEY 约束\"FK_CB_PROJECTFUND_PROJECTMEDIUM\"冲突");
              if(error != -1)
              {
                  HttpServletResponse response = ServletActionContext.getResponse();
                  response.setContentType("text/html; charset=utf-8");
                  PrintWriter out = response.getWriter();
                  out.println("<script type=\"text/javascript\">");
                  out.println("alert(\"该条数据不存在或已删除！\");");
                  out.println("window.location.href='mediumCastDetailList.action'");
                  out.println("</script>");
                  out.flush();
                  out.close();
              }
              else
              {
                  throw new RuntimeException(e);
              }
              
        }
        return SUCCESS;
    }
    
    /**
     * 费用删除
     * 
     * @return
     */
    public String delCharges()
    {
        chargeService.delProjectMedioPrice(proMedID);

        return SUCCESS;
    }
    
    /**
     * 取得下拉框的值
     * @return
     */
    public String getSelectValus()
    {
        Map condition = new HashMap();
        condition.put("proMedID", proMedID);
        condition.put("costType", costType);
        try{
        dics = chargeService.getSubCostTypeByProMedIDCostType(condition);
        }catch (Exception e) {
            e.printStackTrace();
        }
        
        return SUCCESS;
    }
    
    /**
     * 根据费用类型和费用子类取得资金类型列表
     * @return
     */
    public String getFundTypeList()
    {
        Dictionary dic = DatadicContext.getInstance().getDatadicObject(costSubtype, "FYLX");
        if(dic != null)
        {
            // 资金类型
            List<Dictionary> allFundType = DatadicContext.getInstance().getDicDataListByCode("ZJLX");
            
            fundTypes = new ArrayList<Dictionary>();
            for(Dictionary item : allFundType)
            {
                if(item.getExtAttr1().equals(dic.getExtAttr1()))
                {
                    if("2".equals(dic.getExtAttr1()) && "6".equals(item.getId()))
                    {
                        continue;
                    }
                    fundTypes.add(item);
                }
            }
        }
        
        return SUCCESS;
    }
    
    /**
     * 根据资金类型判断是否展示刊例
     * @return
     */
    public String getDictionaryById()
    {
        // 资金类型
        dictionary = DatadicContext.getInstance().getDatadicObject(fundType, "ZJLX");
        
        return SUCCESS;
    }
    
    /**
     * 根据资金类型判断是否展示刊例
     * @return
     */
    public String initEditCharges()
    {
        // 费用类型
        Map condition = new HashMap();
        condition.put("proMedID", proMedID);
        
        // 费用子类
        dics = chargeService.getCostTypeByProMedID(condition);
        if(dics == null)
        {
            dics = new ArrayList<Dictionary>();
        }
        
        // 取得项目媒介刊例总价
        projectMedium = chargeService.getProjectMediumByProMedID(proMedID);
        return SUCCESS;
    }
    
    /**
     * 取得预算额及费用使用折扣
     * @return
     */
    public String ajaxGetCharges()
    {
        // 取得费用信息
        charges = chargeService.getChargesByProMedID(proMedID);
        
        return SUCCESS;
    }
    
    
    /**
     * 取得预算额及费用使用折扣
     * @return
     */
    public String ajaxGetSourcePlanyear()
    {
        Map condition = new HashMap();
        condition.put("proMedID", proMedID);
        condition.put("costType", costType);
        condition.put("costSubtype", costSubtype);
        
        Dictionary dic = DatadicContext.getInstance().getDatadicObject(costSubtype, "FYLX");
        
        try {
        if(dic != null)
        {
            charge = new Charge();
            
            // 媒体预算
            if("2".equals(dic.getExtAttr1()))
            {
                SourcePlanYear sourceplanyear = chargeService.getMediaSummariePcc(condition);
                //MediaPrice mediaPrice = chargeService.getMediaPriceByProMedID(proMedID);
                
                if(sourceplanyear != null)
                {
                    // 常规价格常规折扣投放  常规价格特殊折扣存放 
                    if("1".equals(fundType) || "2".equals(fundType))
                    {
                        double amount = 0f;
                        if(sourceplanyear.getUnPromotionAmount() != null)
                        {
                            amount = sourceplanyear.getUnPromotionAmount();
                        }
                        if(sourceplanyear.getUnPromotionAmountUsed() != null)
                        {
                            amount = amount - sourceplanyear.getUnPromotionAmountUsed();
                        }
                        charge.setAmount(amount);
                        
                        // 预算使用折扣
                        Map usedRatioCondition = new HashMap();
                        usedRatioCondition.put("proMedID", proMedID);
                        usedRatioCondition.put("saleType", "1");
                        LevelRule levelRule = chargeService.getUnPromotionUsedRatio(usedRatioCondition);
                        charge.setUsedRatio(levelRule == null ? 100f : levelRule.getLevelDiscount());
                        
                        // 最多抵扣刊例价数量
//                        charge.setDkkanliCount(amount + amount * (100 - charge.getUsedRatio())/100);
                        charge.setDkkanliCount(Arith.add(amount, Arith.div(Arith.mul(amount, Arith.sub(100, charge.getUsedRatio())), 100)));
                    }
                    
                    // 年度返还资源投放
                    if("4".equals(fundType))
                    {
                        double amount = 0f;
                        Date today = new Date();
                        String returnSourceAmountTime = sourceplanyear.getReturnSourceAmountTime();
                        if(returnSourceAmountTime.length() > 10)
                        {
                            returnSourceAmountTime = returnSourceAmountTime.substring(0, 10);
                        }
                        Date promotionCLastValidDate = StringUtils.string2Date(returnSourceAmountTime, "yyyy-MM-dd");
                        if(today.getTime() <= promotionCLastValidDate.getTime())
                        {
                            if(sourceplanyear.getReturnSourceAmount() != null)
                            {
                                amount = sourceplanyear.getReturnSourceAmount();
                            }
                            if(sourceplanyear.getReturnSourceAmountUsed() != null)
                            {
                                amount = amount - sourceplanyear.getReturnSourceAmountUsed();
                            }
                        }
                        
                        charge.setAmount(amount);
                        
                        // 预算使用折扣
                        double usedRatio = sourceplanyear.getReturnSourceUsedRatio();
                        charge.setUsedRatio(usedRatio);
                        
                        // 最多抵扣刊例价数量
//                        charge.setDkkanliCount(amount + amount * (100 - usedRatio)/100);
                        charge.setDkkanliCount(Arith.add(amount, Arith.div(Arith.mul(amount, Arith.sub(100, usedRatio)), 100)));
                    }
                    // 常规配赠资源投放
                    if("5".equals(fundType))
                    {
                        double amount = 0f;
                        Date today = new Date();
                        String promotionAmountTime = sourceplanyear.getPromotionAmountTime();
                        if(promotionAmountTime.length() > 10)
                        {
                            promotionAmountTime = promotionAmountTime.substring(0, 10);
                        }
                        Date promotionBLastValidDate = StringUtils.string2Date(promotionAmountTime, "yyyy-MM-dd");
                        if(today.getTime() <= promotionBLastValidDate.getTime())
                        {
                            if(sourceplanyear.getPromotionAmount() != null)
                            {
                                amount = sourceplanyear.getPromotionAmount();
                            }
                            if(sourceplanyear.getPromotionAmountUsed() != null)
                            {
                                amount = amount - sourceplanyear.getPromotionAmountUsed();
                            }
                        }
                        
                        charge.setAmount(amount);
                        
                        // 预算使用折扣
                        double usedRatio = sourceplanyear.getPromotionUsedRatio();
                        charge.setUsedRatio(usedRatio);
                        
                        // 最多抵扣刊例价数量
//                        charge.setDkkanliCount(amount + amount * (100 - usedRatio)/100);
                        charge.setDkkanliCount(Arith.add(amount, Arith.div(Arith.mul(amount, Arith.sub(100, usedRatio)), 100)));
                    }
                    // 增量资源投放
                    if("9".equals(fundType))
                    {
                        float amount = 0f;

                        Date today = new Date();
                        String increPromotionAmountTime = sourceplanyear.getIncrePromotionAmountTime();
                        if(increPromotionAmountTime.length() > 10)
                        {
                            increPromotionAmountTime = increPromotionAmountTime.substring(0, 10);
                        }
                        Date promotionBLastValidDate = StringUtils.string2Date(increPromotionAmountTime, "yyyy-MM-dd");
                        if(today.getTime() <= promotionBLastValidDate.getTime())
                        {
                            if(sourceplanyear.getIncrePromotionAmount() != null)
                            {
                                amount = sourceplanyear.getIncrePromotionAmount().floatValue();
                            }
                            if(sourceplanyear.getIncrePromotionAmountUsed() != null)
                            {
                                amount = amount - sourceplanyear.getIncrePromotionAmountUsed().floatValue();
                            }
                        }
                        
                        charge.setAmount(amount);
                        
                        // 预算使用折扣
                        float usedRatio = sourceplanyear.getIncrePromotionUsedRatio().floatValue();
                        charge.setUsedRatio(usedRatio);
                        
                        // 最多抵扣刊例价数量
//                        charge.setDkkanliCount(amount + amount * (100 - usedRatio)/100);
                        charge.setDkkanliCount(Arith.add(amount, Arith.div(Arith.mul(amount, Arith.sub(100, usedRatio)), 100)));
                    }
                    
                    charge.setId(sourceplanyear.getId());
                }
            }
            // 公共预算
            else
            {
                fundBudget = chargeService.getMediaSummarieByYd(condition);
                
                if(fundBudget != null)
                {
                    double amount = 0f;
                    if(fundBudget.getBudget() != null)
                    {
                        amount = fundBudget.getBudget();
                    }
                    if(fundBudget.getUsedBudget() != null)
                    {
                        amount = Arith.sub(amount, fundBudget.getUsedBudget());
                    }
                    charge.setAmount(amount);
                    
                    // 预算使用折扣
                    charge.setUsedRatio(100);
                    
                    // 最多抵扣刊例价数量
                    charge.setDkkanliCount(0);
                    
                    charge.setId(fundBudget.getFundbudgetId());
                }
            }
        }
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        
        return SUCCESS;
    }
    
    public List<Dictionary> getDics()
    {
        return dics;
    }

    public void setDics(List<Dictionary> dics)
    {
        this.dics = dics;
    }

    public String getSelectType()
    {
        return selectType;
    }

    public void setSelectType(String selectType)
    {
        this.selectType = selectType;
    }

    public String getParentId()
    {
        return parentId;
    }
    public void setParentId(String parentId)
    {
        this.parentId = parentId;
    }
    public List<Dictionary> getFundTypes()
    {
        return fundTypes;
    }

    public void setFundTypes(List<Dictionary> fundType)
    {
        this.fundTypes = fundType;
    }
    public List<Charge> getCharges()
    {
        return charges;
    }

    public void setCharges(List<Charge> charges)
    {
        this.charges = charges;
    }
    
    public Integer getPriceId()
    {
        return priceId;
    }

    public void setPriceId(Integer priceId)
    {
        this.priceId = priceId;
    }

    public String getCostType()
    {
        return costType;
    }

    public void setCostType(String costType)
    {
        this.costType = costType;
    }

    public String getCostSubtype()
    {
        return costSubtype;
    }

    public void setCostSubtype(String costSubtype)
    {
        this.costSubtype = costSubtype;
    }
    public List<Dictionary> getCostSubtypes()
    {
        return costSubtypes;
    }

    public void setCostSubtypes(List<Dictionary> costSubtypes)
    {
        this.costSubtypes = costSubtypes;
    }
}
